package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {
    @Reference
    private SetMealService setMealService;
    @Autowired
    private JedisPool jedisPool;
    /**
     * 查询套餐
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){
        List<Setmeal> setmeals=new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try(Jedis jedis = jedisPool.getResource();){
        //从redis中取
        String jedisjson = jedis.get("setmeals");
        if (null==jedisjson){//如果没有
            //rpc调用查询所有套餐
             setmeals = setMealService.findAll();
            log.info("<<<<<<<<<<<<<<<<<<<<<从数据库获取的所有套餐数据>>>>>>>>>>>>>>>>");
            //将集合转json存入redis
            String json = objectMapper.writeValueAsString(setmeals);
            jedis.set("setmeals",json);
            return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS,setmeals);
        }//如果有就直接取
        String json = jedis.get("setmeals");
        log.info("<<<<<<<<<<<<<<<从redis中获取的所有套餐数据>>>>>>>>>>>>>>>>>>>>");
             setmeals= objectMapper.readValue(json,List.class);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS,setmeals);
    }
    @GetMapping("/findById")
    public Result findById(Integer id){
        Setmeal setmeal = new Setmeal();
        ObjectMapper objectMapper = new ObjectMapper();
        try(Jedis jedis = jedisPool.getResource();){
            String json = jedis.get("setmeal"+id);
            if (null==json){
        //rpc调用查询数据
         setmeal = setMealService.findById(id);
         log.info("<<<<<<<<<<<<<<<<<<<<<从数据库获取的单个套餐数据>>>>>>>>>>>>>>>>");
         String s = objectMapper.writeValueAsString(setmeal);
         jedis.set("setmeal"+id,s);
            }
            String s = jedis.get("setmeal"+id);
            setmeal= objectMapper.readValue(s,Setmeal.class);
            log.info("<<<<<<<<<<<<<<<从redis中获取的单个套餐数据>>>>>>>>>>>>>>>>>>>>");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}
